package UI;

import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPasswordField;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JCheckBox;
import javax.swing.SwingConstants;

import threads.BaseRunnableBCBS;
import Logic.SQLReader;
import UI.BaseModels.BCBSPanel;
import UI.BaseModels.HeaderLabel;
import UI.BaseModels.ReturnToAdminMenuButton;

import java.awt.Font;
import java.sql.SQLException;

/**
 * The Class CreateUserPanel holds different buttons and methods to create an account.
 * 
 */
public class CreateUserPanel extends BCBSPanel {

	
	private static final long serialVersionUID = -8905009654628011758L;
	
	private JTextField fldFirstName;
	
	
	private JTextField fldLastName;
	
	private JTextField fldUsername;
	
	private JPasswordField pwdPassword;
	
	private JTextField fldInitialBalance;
	
	private JCheckBox adminCheckBox;
	
	private JButton btnCreateProfile;
	
	private String emailmatch;

	public CreateUserPanel() {

		HeaderLabel header = new HeaderLabel("User Creation");
		this.add(header);

		ReturnToAdminMenuButton rtmm = new ReturnToAdminMenuButton();
		this.add(rtmm);
		
		emailmatch = "(.*)@student.cbs.dk";

		fldFirstName = new JTextField();
		fldFirstName.setHorizontalAlignment(SwingConstants.CENTER);
		fldFirstName.setBounds(130, 59, 165, 25);
		this.add(fldFirstName);
		fldFirstName.setColumns(10);

		fldLastName = new JTextField();
		fldLastName.setHorizontalAlignment(SwingConstants.CENTER);
		fldLastName.setBounds(130, 95, 165, 25);
		this.add(fldLastName);
		fldLastName.setColumns(10);

		fldUsername = new JTextField();
		fldUsername.setHorizontalAlignment(SwingConstants.CENTER);
		fldUsername.setBounds(130, 131, 165, 25);
		this.add(fldUsername);
		fldUsername.setColumns(10);

		pwdPassword = new JPasswordField();
		pwdPassword.setHorizontalAlignment(SwingConstants.CENTER);
		pwdPassword.setBounds(130, 167, 165, 25);
		this.add(pwdPassword);

		JLabel lblFirstName = new JLabel("First name");
		lblFirstName.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblFirstName.setBounds(10, 57, 110, 25);
		this.add(lblFirstName);

		JLabel lblUsername = new JLabel("CBS E-mail");
		lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblUsername.setBounds(10, 129, 110, 25);
		this.add(lblUsername);

		JLabel lblPassword = new JLabel("Password");
		lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblPassword.setBounds(10, 165, 110, 25);
		this.add(lblPassword);

		btnCreateProfile = new JButton("Create Profile");
		btnCreateProfile.setFont(new Font("Tahoma", Font.BOLD, 15));
		btnCreateProfile
				.addActionListener(new BtnCreateProfileActionListener());
		btnCreateProfile.setBounds(60, 292, 182, 35);
		this.add(btnCreateProfile);

		JLabel lblLastName = new JLabel("Last name");
		lblLastName.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblLastName.setBounds(10, 93, 110, 25);
		add(lblLastName);

		fldInitialBalance = new JTextField();
		fldInitialBalance.setHorizontalAlignment(SwingConstants.CENTER);
		fldInitialBalance.setBounds(130, 203, 70, 25);
		add(fldInitialBalance);
		fldInitialBalance.setColumns(10);

		JLabel lblInitialBalance = new JLabel("Initial balance");
		lblInitialBalance.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblInitialBalance.setBounds(10, 201, 110, 25);
		add(lblInitialBalance);

		adminCheckBox = new JCheckBox("");
		adminCheckBox.setBounds(147, 241, 21, 21);
		add(adminCheckBox);

		add(feedbackLabel);

		JLabel administratorLabel = new JLabel("Administrator?");
		administratorLabel.setFont(new Font("Tahoma", Font.PLAIN, 15));
		administratorLabel.setBounds(10, 237, 110, 25);
		add(administratorLabel);
	}

	
	private class BtnCreateProfileActionListener implements ActionListener {
		

		public void actionPerformed(ActionEvent arg0) {
			createUser();
		}
	}
/**
 * Clears every textfield.
 */
	@Override
	public void clearFields() {
		feedbackLabel.setText("");
		fldInitialBalance.setText("");
		pwdPassword.setText("");
		fldUsername.setText("");
		fldLastName.setText("");
		fldFirstName.setText("");
		adminCheckBox.setSelected(false);
	}
	
	/**
	 * This method enables or disables the button used to create a profile.
	 * 
	 *  @param value
	 *  The state to set the button to. If true the button will be enabled. If false the button will be disabled.   
	 */
	public void enableButton(boolean value) {
		if (value) {
			btnCreateProfile.setEnabled(true);
		} else {
			btnCreateProfile.setEnabled(false);
		}
	}
/**
 * Creates a runnable of the type CreateUserRunnable, sets the runnable variable of the panel to the newly created runnable, places it in its own thread and starts the thread.
 * 
 */
	private void createUser() {
		runnable = new CreateUserRunnable();
		Thread t = new Thread(runnable);
		t.start();
	}
/**
	 * See the run-method of this class for details.
	 *
	 */
	private class CreateUserRunnable extends BaseRunnableBCBS {
		
		/**
		 * Checks if all fields in the panel have valid data, then creates a new user with the specified values in the database.
		 *
		 */
		public void run() {
			SQLReader reader = new SQLReader();
			enableButton(false);
			String username = fldUsername.getText().trim();
			String firstname = fldFirstName.getText().trim();
			String lastname = fldLastName.getText().trim();
			char[] password = pwdPassword.getPassword();
			boolean admin = adminCheckBox.isSelected();
			boolean validamount = false;
			double balance = 0;

			try {
				balance = Double.valueOf(fldInitialBalance.getText().trim());
				validamount = true;
			} catch (NumberFormatException e) {
				enableButton(true);
				feedback("Please input valid initial balance!", false);
			}
			try {
				if (!reader.checkEmailAll(username) && validamount) {
					if (username.matches(emailmatch)){
					try {
						if (!stop) {

							reader.addAccount(username, password, balance,
									firstname, lastname, admin);
							clearFields();
							enableButton(true);
							feedback("User added successfully!", true);
						}

					} catch (SQLException e) {
						if (!stop) {
							enableButton(true);
							feedback("Connection error! Try again!", false);
						}
					 }
					}else {
						feedback("E-mail must match CBS structure!", false);
						enableButton(true);
					}
				} else if (validamount && !stop) {

					feedback("E-mail already exists!", false);
					enableButton(true);

				}
			} catch (SQLException e) {
				if (!stop) {
					feedback("Connection error! Try again!", false);
					enableButton(true);
				}
			}

		}
	}
}
